package com.babai.common;

import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class Result {

    public static class Codes {
        public static String SUCCESS = "0000";
        public static String PASSWORD_ERROR = "1001";
        public static String OTHERS = "9999";

        public static String REDIS_ERROR = "2001";

        public static String WX_NEED_PHONENUMBER = "3001";
    }

    private String code;
    private String msg;
    private Object data;

    private Object extraData;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public Result(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public static Result success() {
        return new Result(Codes.SUCCESS, "success");
    }

    public static Result success(String msg) {
        Result result = success();
        result.setMsg(msg);
        return result;
    }

    public static Result error() {
        return new Result(Codes.OTHERS, "error");
    }

    public Result addCode(String code) {
        this.setCode(code);
        return this;
    }

    public Result addMsg(String msg) {
        this.setMsg(msg);
        return this;
    }

    public Result addData(Object data) {
        this.setData(data);
        return this;
    }

    public Object getExtraData() {
        return extraData;
    }

    public void setExtraData(Object extraData) {
        this.extraData = extraData;
    }

    public Result addExtraData(Object data) {
        this.setExtraData(data);
        return this;
    }

    public void print(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.print(JSONObject.toJSONString(this));
        out.flush();
        out.close();
    }
}
